import axios from 'axios';
import { Loading,Notification } from 'element-ui';

let reqnum = [],loadinginstace;

function _closeLoading(){
	reqnum=[];
	loadinginstace?loadinginstace.close():{};
}

function _filterCode(data){
	try{
		let code = data.code;
		//token失效，跳转到登录页面
		if(code===1100){
			window.localStorage.setItem('token','');
			window.location = window.location.origin + '/login.html';
		}else if(code !== 0){
			Notification.error({
				title: '请求出错',
                duration:800,
	          	message: data.msg,
	          	offset: 50
	        })
		}
	}catch(e){}
	
}
function _interceptors() {
	//http请求拦截器
	axios.interceptors.request.use(config => {
		//添加header登录认证
		config.headers.Authorization='Bearer '+window.localStorage.getItem('token');
		loadinginstace = Loading.service({ fullscreen: true });//调用加载组件
		//多个请求loadding监控
		reqnum.push('');
		return config;
	}, error => {
		_closeLoading();
		return Promise.reject(error);
	})
	// http响应拦截器
	axios.interceptors.response.use(res => {
		_filterCode(res.data);
		reqnum.splice(0,1);
		//请求全部成功
		if(reqnum.length==0) _closeLoading();
		return res;
	}, error => {
		_closeLoading();
		Notification.error({
			title: '服务器错误',
          	message: error.status,
          	offset: 50
        })
		return Promise.reject(error);
	})
}

export default {
	interceptors:_interceptors
}
